package com.bwie.rent.config;

import com.alibaba.fastjson.JSON;
import com.bwie.rent.dao.HouseRentDao;
import com.bwie.rent.entity.HouseRentEntity;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author By:HDsir
 * @date 2022/3/23
 */
@Component
@SuppressWarnings("all")
public class MyRunner implements ApplicationRunner {
    @Autowired
    private HouseRentDao houseRentDao;
    @Autowired
    private RestHighLevelClient client;
    @Override
    public void run(ApplicationArguments args) throws Exception {
        List<HouseRentEntity> houseRentEntities = houseRentDao.selectList(null);
        if (houseRentEntities!=null) {
            BulkRequest bulkRequest = new BulkRequest("rent");
            for (HouseRentEntity houseRentEntity : houseRentEntities) {
                IndexRequest request = new IndexRequest();
                request.id(houseRentEntity.getHouseId()+"");
                String jsonString = JSON.toJSONString(houseRentEntity);
                request.source(jsonString, XContentType.JSON);
                bulkRequest.add(request);
            }
            BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
            System.out.println("---------------------项目启动时数据同步到ElasticSearch......---------------------");
        }

    }
}
